from flask import Flask, render_template, request, session, redirect, make_response, jsonify, url_for
from flask_session import Session
from frameworks.utils.JsonResult import *
from frameworks.cores.LoadClass import *
from frameworks.cores.Config import *
from frameworks.utils.JsonResult2 import *
from controller.ApiController import *
from frameworks.utils.RedisUtil import *
from werkzeug.utils import secure_filename
import json
import os
import hashlib

redis = RedisUtil()
import numpy as np

"""
from keras.models import load_model
from keras.losses import mean_squared_error

# 加载模型
model = load_model('ai/my_ai_model.h5')

"""
server = Flask(__name__)


# from gevent import monkey

# 将python标准的io方法，都替换成gevent中的同名方法，遇到io阻塞gevent自动进行协程切换
# monkey.patch_all()

def create_app():
    app = Flask(__name__)
    return app


app = create_app()
app.config['JSON_AS_ASCII'] = False
app.config['SESSION_TYPE'] = 'filesystem'

Session(app)

basepath = os.path.join(os.path.dirname(__file__))
config = Config(basepath)

apimap = config.getApi()
env = apimap["base"]
print(env)

print(basepath)

jsonResult = JsonResult2()

loader = LoadClass()

from views.common import common
from views.finance import finance
from views.strategy import strategy
from views.recalltest import recalltest
from views.prestock import prestock

app.register_blueprint(common, url_prefix='/common')
app.register_blueprint(finance, url_prefix='/finance')
app.register_blueprint(strategy, url_prefix="/strategy")
app.register_blueprint(recalltest, url_prefix="/recalltest")
app.register_blueprint(prestock, url_prefix="/prestock")

@app.route(env + "/", methods=['GET', 'POST'])
def index():
    css = "layui-this"
    indexcss = css
    fupancss = ""
    catcss = ""
    zhangtingcss = ""
    zhinengcss = ""
    if "username" in session:
        username = session['username']
    else:
        username = ""
    content = loader.load("controller.calc.TalkController", "TalkController", {
        "func": "getDaPan"
    })
    return render_template('/front/index.html',
                           username=username,
                           indexcss=indexcss,
                           catcss=catcss,
                           fupancss=fupancss,
                           zhangtingcss=zhangtingcss,
                           zhinengcss=zhinengcss,
                           talkcontent=content
                           )


@app.route(env + "/member", methods=['GET', 'POST'])
def member_index():
    if session.get("username") != None:
        pagename = request.args.get("pagename", "/finance/")
        timestamp = int(time.time())
        # 获取其他参数
        other_params = request.args.to_dict()
        # 移除已经处理的 pagename 参数
        if 'pagename' in other_params:
            del other_params['pagename']
        # 构建包含其他参数的 URL
        new_url = pagename + "?"
        for key in other_params.keys():
            new_url += key + "=" + other_params[key] + "&"
        print(new_url)
        return render_template('index.html', username=session['username'] ,timestamp=timestamp, pagename=new_url)
    else:
        return redirect("/",code=302,Response=None)

@app.route(env + "/detail", methods=['GET', 'POST'])
def front():
    css = "layui-this"
    indexcss = css
    fupancss = ""
    catcss = ""
    zhangtingcss = ""
    zhinengcss = ""
    if "username" in session:
        username = session['username']
    else:
        username = ""
    # print(serverlist)
    apiController = ApiController()
    newParam = {}
    code = request.args.get("code", "600009")
    for key in request.args.keys():
        newParam[key] = request.args.get(key, "")
    newParam["code"] = code
    obj = apiController.getHomePageData(newParam)
    multicode = apiController.getMultiCode(code)
    return render_template('front/detail.html',
                           code=code,
                           multicode=multicode,
                           shcode=obj["code"].lower(),
                           content=obj,
                           username=username,
                           indexcss=indexcss,
                           catcss=catcss,
                           fupancss=fupancss,
                           zhangtingcss=zhangtingcss,
                           zhinengcss=zhinengcss
                           )


@app.route(env + "/front/fupan", methods=['GET'])
def fupan():
    css = "layui-this"
    indexcss = ""
    fupancss = css
    catcss = ""
    zhangtingcss = ""
    zhinengcss = ""
    # print(serverlist)
    apiController = ApiController()
    obj = apiController.getFupan()
    return render_template('front/fupan.html',
                           content=obj,
                           indexcss=indexcss,
                           catcss=catcss,
                           fupancss=fupancss,
                           zhangtingcss=zhangtingcss,
                           zhinengcss=zhinengcss,
                           username=session['username']
                           )


@app.route(env + "/front/autoselect", methods=['GET'])
def autoselect():
    css = "layui-this"
    indexcss = ""
    fupancss = ""
    catcss = css
    zhangtingcss = ""
    zhinengcss = ""
    # print(serverlist)
    apiController = ApiController()
    obj = apiController.getAutoSelect()
    print(obj)
    return render_template('front/auto_select.html',
                           content=obj,
                           indexcss=indexcss,
                           catcss=catcss,
                           fupancss=fupancss,
                           zhangtingcss=zhangtingcss,
                           zhinengcss=zhinengcss,
                           username=session['username']
                           )


@app.route(env + "/front/model", methods=['GET'])
def model():
    css = "layui-this"
    indexcss = ""
    fupancss = ""
    catcss = ""
    zhangtingcss = ""
    zhinengcss = css
    apiController = ApiController()
    obj = apiController.getModels()
    return render_template('front/model.html',
                           content=obj,
                           indexcss=indexcss,
                           catcss=catcss,
                           fupancss=fupancss,
                           zhangtingcss=zhangtingcss,
                           zhinengcss=zhinengcss,
                           username=session['username']
                           )


@app.route(env + "/front/zhangting", methods=['GET'])
def zhangting():
    css = "layui-this"
    indexcss = ""
    fupancss = ""
    catcss = ""
    zhangtingcss = css
    zhinengcss = ""
    # print(serverlist)
    num = request.args.get("num", 1)
    ck = "zhangting_list_" + str(num)
    obj = redis.vget(ck)
    if obj == None:
        obj = []
    else:
        obj = json.loads(obj)
    if num == "9" or num == 9:
        numstr = "多"
    else:
        numstr = num
    if "username" not in session:
        username = ""
    else:

        username = session["username"]
    return render_template('front/zhangting.html',
                           num=numstr,
                           content=obj,
                           indexcss=indexcss,
                           catcss=catcss,
                           fupancss=fupancss,
                           zhangtingcss=zhangtingcss,
                           zhinengcss=zhinengcss,
                           username=username
                           )


@app.route(env + "/front/dayscore", methods=['GET'])
def dayscore():
    css = "layui-this"
    indexcss = ""
    fupancss = ""
    catcss = ""
    zhangtingcss = css
    zhinengcss = ""
    ck = "day_score_cache"
    obj = redis.vget(ck)
    if obj == None:
        obj = []
    else:
        obj = json.loads(obj)
    obj = reversed(sorted(obj, key=lambda x: x['score']))
    if "username" not in session:
        username = ""
    else:

        username = session["username"]
    return render_template('front/dayscore.html',
                           content=obj,
                           indexcss=indexcss,
                           catcss=catcss,
                           fupancss=fupancss,
                           zhangtingcss=zhangtingcss,
                           zhinengcss=zhinengcss,
                           username=username
                           )


@app.route(env + "/front/day_money_score", methods=['GET'])
def day_money_score():
    css = "layui-this"
    indexcss = ""
    fupancss = ""
    catcss = ""
    zhangtingcss = css
    zhinengcss = ""
    cachekey = request.args.get("cachekey", "day_all_score_cache")
    obj = redis.vget(cachekey)
    if obj == None:
        obj = []
    else:
        obj = json.loads(obj)
    ordfile = request.args.get("ordfile", "score")
    ascord = request.args.get("asc", "desc")
    if ascord == "desc":
        obj = reversed(sorted(obj, key=lambda x: x[ordfile]))
    else:
        obj = sorted(obj, key=lambda x: x[ordfile])
    if "username" not in session:
        username = ""
    else:

        username = session["username"]
    return render_template('front/days_money_score.html',
                           content=obj,
                           indexcss=indexcss,
                           catcss=catcss,
                           fupancss=fupancss,
                           zhangtingcss=zhangtingcss,
                           zhinengcss=zhinengcss,
                           username=username
                           )


@app.route(env + "/login/api", methods=['POST'])
def loginapi():
    quert_json = request.get_data(as_text=True)
    userinfo = json.loads(quert_json)
    session['username'] = userinfo["username"]
    md = hashlib.md5()  # 获取一个md5加密算法对象
    md.update(userinfo["password"].encode('utf-8'))  # 制定需要加密的字符串
    rs = loader.load("controller.ServersController", "ServersController", {
        "func": "getAllData",
        "data": {"username": userinfo["username"], "password": md.hexdigest()},
        "model": "users",
        "fields": "*"
    })
    if len(rs) > 0:
        session["userid"] = rs[0]["id"]
        return JsonResult.setOk("登录成功", "{}")
    else:
        return JsonResult.setError("没有该用户，或者密码错误")


@app.route(env + "/reg/api", methods=['POST'])
def regapi():
    quert_json = request.get_data(as_text=True)
    userinfo = json.loads(quert_json)
    md = hashlib.md5()  # 获取一个md5加密算法对象
    md.update(userinfo["password"].encode('utf-8'))  # 制定需要加密的字符串
    loader.load("controller.ServersController", "ServersController", {
        "func": "add",
        "data": {"username": userinfo["username"], "password": md.hexdigest()},
        "model": "users"
    })
    session['username'] = userinfo["username"]
    return JsonResult.setOk("注册成功", "{}")


@app.route(env + "/logout", methods=['GET'])
def logout():
    session["username"] = ""
    session.clear()
    return redirect('/', code=302, Response=None)


@app.route(env + "/login", methods=['GET', 'POST'])
def login():
    return render_template("front/login.html")


@app.route(env + "/reg", methods=['GET', 'POST'])
def reg():
    return render_template("front/reg.html")


@app.route(env + "/aacharts", methods=['GET'])
def aacharts():
    ck = request.args.get("ck", "")
    al = redis.vget(ck)
    if al == None:
        return jsonResult.setOk([], "获取成功")
    else:
        print("=======read cache===============")
        return jsonResult.setOk(al, "获取成功")


import os
import hashlib

# 设置允许的文件格式
ALLOWED_EXTENSIONS = set(['png', 'jpg', 'JPG', 'PNG', 'bmp', "xlsx", "jpeg"])


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS


def get_ext(filename):
    print(filename)
    return os.path.splitext(filename)[1]


@app.route('/upload_orc_file', methods=['POST'])  # 添加路由
def upload_orc_file():
    if request.method == 'POST':
        f = request.files['file']

        print(f.filename)
        print(allowed_file(f.filename))

        if not (f and allowed_file(f.filename)):
            return jsonify({"error": 1001, "msg": "请检查上传的图片类型，仅限于png、PNG、jpg、JPG、bmp、xlsx"})

        imgpath = "/root/images/"
        print(imgpath)

        upload_path1 = imgpath + f.filename  # 注意：没有的文件夹一定要先创建，不然会提示没有该路径
        print(upload_path1)
        f.save(upload_path1)

        return jsonify({'code': 200, "data": upload_path1}), 200


@app.route('/display/img/<string:filename>', methods=['GET'])
def display_img(filename):
    if request.method == 'GET':
        imgpath = "/root/images/"
        image_data = open(imgpath + filename, "rb").read()
        response = make_response(image_data)
        response.headers['Content-Type'] = 'image/jpg'
        return response
    else:
        pass


"""
@app.route('/predict', methods=['POST'])
def predict():
    data = request.json
    features = np.array(data['features']).reshape(1, -1)
    prediction = model.predict(features)
    # 返回预测结果
    return jsonify({
        'success': True,
        'prediction': float(prediction[0][0])  # 将预测值转换为浮点数返回
    })
"""

if __name__ == "__main__":
    app.run()
